//
//  ShowImageViewController.m
//  MyTravel
//
//  Created by Hunk on 11-5-27.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "ShowImageViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "AsyncLoadingImageView.h"
#import "NetworkManager.h"
#import "NSString+URLEncoding.h"

#define TAG_PAGECONTROL (111)
#define TAG_SCROLLVIEW (124)

#define KEY_NAME        @"name"
#define KEY_IMAGE       @"image"
#define KEY_DESCRIPTION @"description"

@interface ShowImageViewController (Private)

- (void)addItems:(UIScrollView*)scrollView item:(NSArray*)itemArray;

-(void)addLabelOnCell:(UITableViewCell*)cell 
				 text:(NSString*)text
				frame:(CGRect)frame 
			  bgColor:(UIColor*)bgColor 
			textColor:(UIColor*)textColor 
		   fontOfSize:(UIFont*)fontOfSize 
		lineBreakMode:(UILineBreakMode)lineBreakMode
		textAlignment:(UITextAlignment)textAlignment;
@end

@implementation ShowImageViewController
@synthesize showImageStatus, arrayShowImage, arrayInfo, textViewString;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    SAFE_RELEASE(arrayShowImage)
    SAFE_RELEASE(arrayInfo)
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    if(showImageStatus == ShowImageStatus_JourneyDetails)
    {
        self.title = @"详细安排";
        
        UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)
                                                              style:UITableViewStylePlain];
        [tableView setDelegate:self];
        [tableView setDataSource:self];
        [self.view addSubview:tableView];
        [tableView release];
    }
    else if(showImageStatus == ShowImageStatus_JourneyDetails_TextView)
    {
        self.title = @"日程安排";
        
        // Background view
        UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)];
        [bgImageView setImage:[[UIImage imageNamed:@"CellBackground.png"]
                               stretchableImageWithLeftCapWidth:5 topCapHeight:5]];
        [self.view addSubview:bgImageView];
        [bgImageView release];

        // Border view
        UIView* borderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)];
        [borderView setBackgroundColor:[UIColor clearColor]];
        borderView.layer.borderWidth = 2.0;
        borderView.layer.borderColor = [UIColor brownColor].CGColor;
        [self.view addSubview:borderView];
        [borderView release];
        
        // TextView
        UITextView* textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)];
        [textView setBackgroundColor:[UIColor clearColor]];
        [textView setShowsVerticalScrollIndicator:YES];
        [textView setTextColor:TEXTCOLOR];
        [textView setFont:[UIFont fontWithName:@"AmericanTypewriter" size:18]];
        [textView setTextAlignment:UITextAlignmentLeft];
        [textView setEditable:NO];
        [textView setText:textViewString];
        [self.view addSubview:textView];
        [textView release];
    }
    else
    {
        // Init scrollView
        UIScrollView* scrollView = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)] autorelease];
        scrollView.pagingEnabled = YES;
        scrollView.userInteractionEnabled = YES;
        scrollView.scrollEnabled = YES;
        [scrollView setShowsHorizontalScrollIndicator:NO];
        [scrollView setShowsVerticalScrollIndicator:NO];
        [scrollView setContentSize:CGSizeMake(320 * [arrayShowImage count], 400)];
        scrollView.delegate = self;
        [self.view addSubview:scrollView];
        
        // Add items to scrollView
        [self addItems:scrollView item:arrayShowImage];
        
        // Page control
        UIPageControl* pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 400, 320, 16)];
        pageControl.backgroundColor = [UIColor blackColor];
        pageControl.hidesForSinglePage = NO;
        pageControl.tag = TAG_PAGECONTROL;
        pageControl.numberOfPages = [arrayShowImage count];
        [self.view addSubview:pageControl];
        [pageControl release];
        
        // Alpha view hide the page control view
        UIView* alphaView = [[UIView alloc] initWithFrame:CGRectMake(0, 400, 320, 16)];
        [alphaView setBackgroundColor:[UIColor clearColor]];
        [self.view addSubview:alphaView];
        [alphaView release];
    }
}

#pragma mark -
#pragma mark addItems:item:
- (void)addItems:(UIScrollView*)scrollView item:(NSArray*)itemArray
{
    for(int i = 0; i < [itemArray count]; i++)
    {
        // Bg view
        UIView* bgView = [[UIView alloc] initWithFrame:CGRectMake(320 * i, 0, 320, 400)];
        bgView.backgroundColor = [UIColor clearColor];
        
        UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
        UIImage* image = [UIImage imageNamed:@"CellBackground.png"];
        image = [image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
        [bgImageView setImage:image];
        [bgView addSubview:bgImageView];
        [bgImageView release];
        
        // Name
        UILabel* nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 35)];
        [nameLabel setBackgroundColor:[UIColor clearColor]];
        [nameLabel setTextColor:[UIColor blackColor]];
        [nameLabel setTextAlignment:UITextAlignmentCenter];
        [nameLabel setFont:[UIFont boldSystemFontOfSize:24]];
        [nameLabel setText:[[arrayShowImage objectAtIndex:i] objectForKey:KEY_NAME]];
        [bgView addSubview:nameLabel];
        [nameLabel release];
        
        // Load and add imageView
        AsyncLoadingImageView* asyncLoadingImageView = [[[AsyncLoadingImageView alloc] initWithFrame:CGRectMake(10, 35, 300, 200)] autorelease];
        [asyncLoadingImageView loadImageFromURLString:[[arrayShowImage objectAtIndex:i] objectForKey:KEY_IMAGE]
                                     placeholderImage:nil];
        asyncLoadingImageView.layer.cornerRadius = 8.0;
        asyncLoadingImageView.layer.masksToBounds = YES;
        [bgView addSubview:asyncLoadingImageView];
        
        // Description
        UILabel* descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, asyncLoadingImageView.frame.origin.y + asyncLoadingImageView.frame.size.height, 300, (400 - (asyncLoadingImageView.frame.origin.y + asyncLoadingImageView.frame.size.height)))];
        [descriptionLabel setBackgroundColor:[UIColor clearColor]];
        [descriptionLabel setTextColor:[UIColor blackColor]];
        [descriptionLabel setTextAlignment:UITextAlignmentCenter];
        [descriptionLabel setFont:[UIFont systemFontOfSize:16]];
        [descriptionLabel setNumberOfLines:10];
        [descriptionLabel setLineBreakMode:UILineBreakModeCharacterWrap];
        [descriptionLabel setText:[[arrayShowImage objectAtIndex:i] objectForKey:KEY_DESCRIPTION]];
        [bgView addSubview:descriptionLabel];
        [descriptionLabel release];
        
        [scrollView addSubview:bgView];
        [bgView release];
    }
}

#pragma mark -
#pragma mark scrollViewDidEndDecelerating
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    UIPageControl* pageControl = (UIPageControl*)[self.view viewWithTag:TAG_PAGECONTROL];

    pageControl.currentPage = scrollView.contentOffset.x / 320;
}

#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{   
    return [arrayInfo count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* infoString = [[[arrayInfo objectAtIndex:indexPath.section] componentsSeparatedByString:@"[TIME]"] objectAtIndex:1];
    
    CGSize size = [infoString sizeWithFont:[UIFont systemFontOfSize:16.0] 
                         constrainedToSize:CGSizeMake(300, 500) 
                             lineBreakMode:UILineBreakModeCharacterWrap];
    return ((size.height + 10) > 50 ? (size.height + 10) : 50);
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    UILabel* labelForHeader = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 30)] autorelease];
//    [labelForHeader setBackgroundColor:[UIColor brownColor]];
//    [labelForHeader setText:[[[arrayInfo objectAtIndex:section] componentsSeparatedByString:@"[TIME]"] objectAtIndex:0]];
//    [labelForHeader setTextAlignment:UITextAlignmentCenter];
//    return labelForHeader;
//}

- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{   
    return [[[arrayInfo objectAtIndex:section] componentsSeparatedByString:@"[TIME]"] objectAtIndex:0];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                   reuseIdentifier:CellIdentifier] autorelease];
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    
    NSString* infoString = [[[arrayInfo objectAtIndex:indexPath.section] componentsSeparatedByString:@"[TIME]"] objectAtIndex:1];
    
    CGSize size = [infoString sizeWithFont:[UIFont systemFontOfSize:16.0] 
                         constrainedToSize:CGSizeMake(300, 500) 
                             lineBreakMode:UILineBreakModeCharacterWrap];
    float fHeight = ((size.height + 10) > 50 ? (size.height + 10) : 50);
    
    // Cell background view
    UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, fHeight)];
    UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, fHeight)];
    [bgImageView setImage:[[UIImage imageNamed:@"CellBackground.png"]
                           stretchableImageWithLeftCapWidth:5 topCapHeight:5]];
    [cellBgView addSubview:bgImageView];
    [bgImageView release];
    [cell setBackgroundView:cellBgView];
    [cellBgView release];
    
    // Description
    [self addLabelOnCell:cell 
                    text:infoString
                   frame:CGRectMake(10, 5, 300, fHeight - 10) 
                 bgColor:[UIColor clearColor] 
               textColor:[UIColor blackColor] 
              fontOfSize:[UIFont systemFontOfSize:16] 
           lineBreakMode:UILineBreakModeCharacterWrap 
           textAlignment:UITextAlignmentLeft];
    
    return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}   

#pragma mark -
#pragma mark addLabelOnCell
-(void)addLabelOnCell:(UITableViewCell*)cell
				 text:(NSString*)text
				frame:(CGRect)frame 
			  bgColor:(UIColor*)bgColor 
			textColor:(UIColor*)textColor 
		   fontOfSize:(UIFont*)fontOfSize 
		lineBreakMode:(UILineBreakMode)lineBreakMode 
		textAlignment:(UITextAlignment)textAlignment
{
	if(!bgColor) bgColor = [UIColor grayColor];
	if(!textColor) textColor = [UIColor blackColor];
	if(!fontOfSize) fontOfSize = [UIFont systemFontOfSize:16];
	if(!text) text = [NSString stringWithString:@"请输入Label内容"];
	
	UILabel* titleLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
	titleLabel.backgroundColor = bgColor;
	titleLabel.textColor = textColor;
	titleLabel.font = fontOfSize;
	titleLabel.lineBreakMode = UILineBreakModeCharacterWrap;
	titleLabel.textAlignment = textAlignment;
	titleLabel.text = text;
    titleLabel.numberOfLines = 10;
	[cell.contentView addSubview:titleLabel];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
